package org.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/manager";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    private static Connection con = null;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("数据库加载异常");
        }
    }

    public void createConnection(){
        try{
            con = DriverManager.getConnection(URL, USER, PASSWORD);
            con.setAutoCommit(true);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static Connection getConnection() throws SQLException {
        /*try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return DriverManager.getConnection(URL,USER,PASSWORD);*/

        try{
            con = DriverManager.getConnection(URL, USER, PASSWORD);
            con.setAutoCommit(true);
        }catch (Exception e){
            System.err.println("数据库连接失败");
            System.out.println(e.getMessage());
        }
        return con;
    }

    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

//package org.example;
//
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//
//public class DBConnection {
//
//    private static final String URL = "jdbc:mysql://localhost:3306/manager?useSSL=false&serverTimezone=UTC";
//    private static final String USER = "root";
//    private static final String PASSWORD = "123456";
//
//    public static Connection getConnection() throws SQLException {
//        try {
//            Class.forName("com.mysql.cj.jdbc.Driver");
//        } catch (ClassNotFoundException e) {
//            throw new RuntimeException("MySQL JDBC Driver not found.", e);
//        }
//        return DriverManager.getConnection(URL, USER, PASSWORD);
//    }
//
//    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
//        try {
//            if (rs != null) rs.close();
//            if (pstmt != null) pstmt.close();
//            if (conn != null) conn.close();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//    }
//}
